package com.xmu.prcs.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.xmu.prcs.dao.PostDao;
import com.xmu.prcs.entity.Post;

/**
 * 
 * @author frequent
 * @version 1.0,2012-3-20
 *
 */
public class PostDaoImpl extends GenericDaoImpl<Post> implements PostDao{

	public PostDaoImpl() {
		super(Post.class);
	}

	public Post getLastestPostOfTopic(int topicId) {
		String sql = "select * from (select * from post where post.idtopic="
					+ topicId
					+ ") t1 where not exists(select * from (select * from post where post.idtopic="
					+ topicId
					+ ") t2 where t2.createtime > t1.createtime) order by t1.idpost desc";
		Query query = getHibernateTemplate().getSessionFactory().getCurrentSession()
					.createSQLQuery(sql).addEntity(Post.class);
		Post post = null;
		List<Post> list = query.list();
		if(list != null && list.size() != 0){
			post = list.get(0);
		}
		return post;
	}
	
	public List<Post> getByProperty(String property, Object object){
		List<Post> list;
		String sql = "from Post as model where model." + property + " = ?";
		list = this.getHibernateTemplate().find(sql, object);
		return list;
	}

	public int countPost(int topicId) {
		String sql = "select count(1) from post p where p.idtopic=" + topicId;
		Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
		Query query = session.createSQLQuery(sql);
		int size;
		if(query.uniqueResult() == null){
			size = 0;
		}
		size = Integer.parseInt((query.uniqueResult().toString()));
		System.out.println("size:" + size);
		return size;
	}

	public List<Post> find4Page(int begin, int size, int topicId) {
		String sql = "select * from post where post.idtopic=" + topicId +" order by post.lastreplytime desc ";
		Query query = getHibernateTemplate().getSessionFactory()
					.getCurrentSession().createSQLQuery(sql).addEntity(Post.class);
		
		query.setFirstResult(begin);
		query.setMaxResults(size);
		return query.list();
	}

}
